import 'package:flutter/material.dart';
import 'package:flutter_time_manager/state/model/todo.dart';
import 'package:flutter_time_manager/state/time_manager_state.dart';
import 'package:flutter_time_manager/widget/my_button_widget.dart';
import 'package:provider/provider.dart';

class AddTodoPage extends StatefulWidget {
  final Todo todo;

  const AddTodoPage({Key key, this.todo}) : super(key: key);

  @override
  _AddTodoPageState createState() => _AddTodoPageState();
}

class _AddTodoPageState extends State<AddTodoPage> {
  final _titleController = TextEditingController();
  final _noteController = TextEditingController();
  final GlobalKey _formKey = GlobalKey<FormState>();
  TimeOfDay _timeOfDay;
  bool _switchSelected = false;

  @override
  void initState() {
    super.initState();
    _titleController.text = widget.todo?.title;
    _noteController.text = widget.todo?.note;
    _timeOfDay = widget.todo != null
        ? TimeOfDay.fromDateTime(widget.todo.taskTime)
        : TimeOfDay.now();
  }

  @override
  Widget build(BuildContext context) {
    final List<dynamic> args = ModalRoute.of(context).settings.arguments;
    final title = widget.todo == null ? const Text("添加") : const Text("修改");
    return Scaffold(
      appBar: AppBar(
        title: title,
      ),
      body: Theme(
        data: ThemeData(
          primaryColor: Colors.blueAccent,
          buttonColor: Colors.blueAccent,
        ),
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(horizontal: 24.0, vertical: 10.0),
          child: Form(
            key: _formKey, //设置globalKey，用于后面获取FormState
            autovalidate: true, //开启自动校验
            child: Column(
              children: <Widget>[
                widget.todo == null ? Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text("添加到全部"),
                    Switch(
                      value: _switchSelected, //当前状态
                      onChanged: (value) {
                        setState(() {
                          _switchSelected = value;
                        });
                      },
                    ),
                  ],
                ) : Container(width: 0.0, height: 0.0),
                const SizedBox(height: 5.0),
                InkWell(
                  onTap: () => _selectTime(context, _timeOfDay),
                  child: InputDecorator(
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: "时间",
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Text(_timeOfDay.format(context)),
                        Icon(
                          Icons.arrow_drop_down,
                          color:
                              Theme.of(context).brightness == Brightness.light
                                  ? Colors.grey.shade700
                                  : Colors.white70,
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 20.0),
                TextFormField(
                  autofocus: true,
                  maxLines: 1,
                  maxLength: 15,
                  controller: _titleController,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: "待办事项",
                    hintText: "",
                  ),
                  validator: (v) {
                    return v.trim().length > 0 ? null : "待办事项不能为空";
                  },
                ),
                const SizedBox(height: 20.0),
                TextFormField(
                  maxLines: 5,
                  maxLength: 100,
                  controller: _noteController,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: "具体",
                    hintText: "具体",
                  ),
                ),
                const SizedBox(height: 28.0),
                widget.todo == null
                    ? Row(
                        children: <Widget>[
                          Expanded(
                            child: Consumer<TimeManager>(
                              builder: (context, timeManager, _) => MyButton(
                                    child: const Text("继 续 添 加"),
                                    onTap: () {
                                      if ((_formKey.currentState as FormState)
                                          .validate()) {
                                        timeManager.saveOrUpdateTodo(
                                          _switchSelected,
                                            null,
                                            args[0],
                                            _titleController.text.trim(),
                                            _noteController.text.trim(),
                                            _timeOfDay);
                                        _showSnackBar(context, "添加成功");
                                        _clearInputText();
                                      }
                                    },
                                  ),
                            ),
                          ),
                        ],
                      )
                    : Container(width: 0.0, height: 0.0),
                Consumer<TimeManager>(
                  builder: (context, timeManager, _) => FlatButton(
                      onPressed: () {
                        if ((_formKey.currentState as FormState).validate()) {
                          timeManager.saveOrUpdateTodo(
                            _switchSelected,
                              widget.todo,
                              args[0],
                              _titleController.text.trim(),
                              _noteController.text.trim(),
                              _timeOfDay);
                          Navigator.of(context).pop();
                        }
                      },
                      child: const Text("保 存")),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _selectTime(BuildContext context, TimeOfDay time) async {
    final TimeOfDay picked = await showTimePicker(
      context: context,
      initialTime: time,
    );
    if (picked != null) {
      setState(() {
        _timeOfDay = picked;
      });
    }
  }

  void _clearInputText() {
    _titleController.clear();
    _noteController.clear();
  }

  void _showSnackBar(BuildContext context, String s) {
    Scaffold.of(context).showSnackBar(
      SnackBar(
        content: Text(s),
        action: SnackBarAction(
          label: '知道了',
          onPressed: () {},
        ),
      ),
    );
  }
}
